"ui";

var themeJs = require("./theme.js");
var sortJs = require("./sort.js");
var networkSourceJs = require("./networkSource.js");
var coloringJs = require("./coloring.js");
var addJs = require("./add.js");

dialogs.setDefaultDialogType("app");

//加入单词对话框
var addView = ui.inflate(
    <vertical padding="16 0">
        <horizontal gravity="center_vertical">
            <text text="单词" textColor="{{themeJs.text2}}"/>
            <horizontal w="*" gravity="right">
                <text text="粗体显示" textColor="{{themeJs.text2}}"/>
                <checkbox id="bold" marginLeft="4" checked="true" />
            </horizontal>
        </horizontal>
        <input id="word" text="" textColor="{{themeJs.text}}" singleLine="true"/>
        <list id="suggest" orientation="horizontal">
            <text id="choice" text="{{this.entry}}" textColor="#29B6F6" foreground="?android:attr/selectableItemBackground" padding="10 0"/>
        </list>
        <horizontal gravity="center_vertical">
            <text text="释义" textColor="{{themeJs.text2}}"/>
            <horizontal w="*" gravity="right">
                <text text="使用网络释义" textColor="{{themeJs.text2}}"/>
                <checkbox id="fromNet" marginLeft="4" marginRight="0" checked="true" />
            </horizontal>
        </horizontal>
        <button id="meaning" text="点击获取释义" gravity="left" style="Widget.AppCompat.Button.Borderless.Colored"/>
        <input id="write" textSize="14" textColor="{{themeJs.text}}"/>
    </vertical>, null, false);

addView.suggest.on("item_bind", function(itemView, itemHolder) {
    itemView.choice.on("click", (view) => {
        addView.word.setText(view.text());
        addView.word.setSelection(view.text().length);
    });
});

//点击获取网络释义
addView.meaning.on("click", () => {
    if (addView.fromNet.checked) {
        threads.start(function() {
            mean = networkSourceJs.getMeaning(addView.word.getText());
            ui.run(() => {
                addView.meaning.setText(coloringJs.getColoringStr(mean.trs == "" ? "没有释义" : mean.trs, "#ff00ff"));
            });
        });
    }
});

//监听输入框变化获取网络释义
var oldSuggest = [];
addView.word.addTextChangedListener(new android.text.TextWatcher({
    afterTextChanged: function(text) {
        networkSourceJs.threadsSuspend(2000, () => {
            sleep(100);
            let suggest = networkSourceJs.getSuggest(addView.word.getText());
            ui.run(() => {
                if (suggest.length == 0) {
                    oldSuggest.splice(0, oldSuggest.length);
                } else {
                    addView.suggest.setDataSource(suggest);
                    oldSuggest = suggest;
                }
            });

            if (addView.fromNet.checked) {
                mean = networkSourceJs.getMeaning(addView.word.getText());
                
                let trs = coloringJs.getColoringStr(mean.trs, "#ff00ff");
                if (trs.toString != addView.meaning.text())
                    ui.run(() => {
                        if (mean.trs == "")
                            addView.meaning.setText("没有释义");
                        else addView.meaning.setText(trs);
                        addView.write.setText(trs);
                    });
            }
        }, () => {
            ui.run(() => {
                oldSuggest.splice(0, oldSuggest.length);
                addView.meaning.setText("获取释义失败，网络连接超时！");
            });
        });
    }
}));

var mean = {
    trs: "",
    en: "",
    am: "",
};

var settingStorage = storages.create("wordbook45qq_setting");
var isFromNet = settingStorage.get("fromNet", true);
addView.fromNet.attr("checked", isFromNet);
showType(isFromNet);

addView.fromNet.on("check", function(checked) {
    isFromNet = checked;
    settingStorage.put("fromNet", isFromNet);

    showType(checked);
});

function showType(checked) {
    if (checked) {
        let trs = addView.write.text();
        mean.trs = trs;
        addView.meaning.setText(trs == "" ? "点击获取释义" : trs);
        addView.meaning.setVisibility(View.VISIBLE);
        addView.write.setVisibility(View.GONE);
    } else {
        addView.meaning.setVisibility(View.GONE);
        addView.write.setVisibility(View.VISIBLE);
    }
}

//加入新单词对话框
var addDialog = dialogs.build({
    customView: addView,
    title: "加入新单词",
    positive: "添加",
    negative: "取消",
    titleColor: themeJs.text,
    wrapInScrollView: false,
    autoDismiss: false
}).on("positive", () => {
    if (addView.word.text() == "") {
        addView.word.setError("单词不能为空");
    } else {
        let list = addWord.getList();
        for (let i in list) {
            if (list[i].word == addView.word.text()) {
                let item = list[i];
                let commonDialog = dialogs.build({
                    title: "单词已存在",
                    content: "是否添加为书签？",
                    positive: "添加书签",
                    neutral: "增加标记",
                    negative: "取消",
                    titleColor: themeJs.text,
                    contentColor: themeJs.text2,
                    wrapInScrollView: false,
                }).on("positive", () => {
                    item.hasMark = true;
                    events.broadcast.emit("update_wordlist_index", i);
                }).on("neutral", function() {
                    list[i].count = item.count == null ? 1 : item.count + 1;
                    events.broadcast.emit("update_wordlist_index", i);
                    sortJs.sortByAny(list, i);
                });
                commonDialog.getView().setBackgroundColor(android.graphics.Color.parseColor(themeJs.layout));
                commonDialog.show();

                resetView();
                return;
            }
        }

        addJs.addWord(list,
            addView.word.text(),
            isFromNet ? mean.trs : addView.write.text(),
            mean.en,
            mean.am,
            addView.bold.isChecked()
        );

        let pos = sortJs.sortByAny(list, list.length - 1);
        if (addWord.fun != null) addWord.fun(list[list.length - 1], pos);
        resetView();
    }
}).on("negative", () => {
    resetView();
});

addView.getParent().getParent().attr("bg", themeJs.layout);

//结束对话框
function resetView() {
    ui.post(() => {
        addView.word.setText("");
        addView.meaning.setText("点击获取释义");
        addView.write.setText("");
        oldSuggest.splice(0, oldSuggest.length);
    }, 50);
    mean = {};
    addDialog.dismiss();
}

var addWord = {
    show: function(list, fun) {
        addWord.getList = function() {
            return list;
        };
        addWord.fun = fun;
        addDialog.show();
    },
    mean: {},
};

module.exports = addWord;